# coding=utf-8
__author__ = '侯展意'

import base64
import json
import warnings
import zlib
from typing import List, Callable
import logging
import sys
import cloudpickle
import time
import socket

from PyQt5.QtGui import QCloseEvent

logger = logging.getLogger(__name__)

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject, QThread, pyqtSignal


class PMQThreadManager(QObject):
    signal_server_message_received = pyqtSignal(dict)
    signal_data_changed = pyqtSignal(str)

    def __init__(self, parent=None, worker: QObject = None):
        super().__init__(parent)
        self.thread_recv = QThread()
        self.worker_recv = worker  # PMGThreadWorker()
        self.worker_recv.moveToThread(self.thread_recv)
        self.thread_recv.started.connect(self.worker_recv.work)
        self.thread_recv.start()

    def shut_down(self):
        print('client quit')
        logger.info('client quit')
        self.worker_recv.on_exit()
        # self.worker_recv.close_socket()
        self.thread_recv.quit()
        self.thread_recv.wait(500)


if __name__ == '__main__':
    from PyQt5.QtWidgets import QTextEdit


    class PMGThreadWorker(QObject):
        signal_print = pyqtSignal(str)

        def __init__(self):
            super(PMGThreadWorker, self).__init__()
            self.quit = False

        def work(self):
            print('start')
            while (1):
                print(123)
                self.signal_print.emit('123')
                self.thread().sleep(1)

                if self.quit:
                    break

        def on_exit(self):
            self.quit = True


    class TextEdit(QTextEdit):
        def __init__(self):
            super(TextEdit, self).__init__()
            self.worker = PMGThreadWorker()
            self.thread_mgr = PMQThreadManager(worker=self.worker)
            self.worker.signal_print.connect(self.append)

        def closeEvent(self, a0: 'QCloseEvent') -> None:
            super().closeEvent(a0)
            self.thread_mgr.shut_down()


    app = QApplication(sys.argv)
    text = TextEdit()
    text.show()
    sys.exit(app.exec_())
